﻿using Framework.SqlSugarCore.Repositories;
using my.abp.Domain.IManagers.User;
using my.abp.Domain.Repositories.User;
using my.abp.Domain.Shared.Entities;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Services;
using Volo.Abp.Uow;

namespace my.abp.Domain.Managers.User
{
	public class SysUserExtOrgManager : DomainService, ISysUserExtOrgManager
	{
		private readonly ISysUserExtOrgRepository _sysUserExtOrgRep;

		public SysUserExtOrgManager(ISysUserExtOrgRepository sysUserExtOrgRep)
		{
			_sysUserExtOrgRep = sysUserExtOrgRep;
		}

		/// <summary>
		/// 获取用户扩展机构集合
		/// </summary>
		/// <param name="userId"></param>
		/// <returns></returns>
		public async Task<List<long>> GetUserExtOrgList(long userId)
		{
			ISugarQueryable<SysUserExtOrg>? queryable = await _sysUserExtOrgRep.AsQueryable();
			return await queryable.Where(u=>u.UserId == userId).Select(u=> u.OrgId).ToListAsync();
		}

		/// <summary>
		/// 更新用户扩展机构
		/// </summary>
		/// <param name="userId"></param>
		/// <param name="extOrgList"></param>
		/// <returns></returns>
		[UnitOfWork]
		public async Task UpdateUserExtOrg(long userId, List<long> extOrgList)
		{
			await _sysUserExtOrgRep.DeleteAsync(u => u.UserId == userId);

			List<SysUserExtOrg> lSysUserExtOrg = new List<SysUserExtOrg>();
			if (extOrgList == null || extOrgList.Count < 1) return;
			extOrgList.ForEach(u =>
			{
				SysUserExtOrg sysUserExtOrg = new SysUserExtOrg();
				sysUserExtOrg.UserId = userId;
				sysUserExtOrg.OrgId = u;
				lSysUserExtOrg.Add(sysUserExtOrg);
			});
			await _sysUserExtOrgRep.InsertRangeAsync(lSysUserExtOrg);
		}

		/// <summary>
		/// 根据用户Id删除扩展机构
		/// </summary>
		/// <param name="userId"></param>
		/// <returns></returns>
		public async Task DeleteUserExtOrgByUserId(long userId)
		{
			await _sysUserExtOrgRep.DeleteAsync(u => u.UserId == userId);
		}

		/// <summary>
		/// 根据机构Id集合删除扩展机构
		/// </summary>
		/// <param name="orgIdList"></param>
		/// <returns></returns>
		public async Task DeleteUserExtOrgByOrgIdList(List<long> orgIdList)
		{
			await _sysUserExtOrgRep.DeleteAsync(u => orgIdList.Contains(u.OrgId));
		}

		/// <summary>
		/// 根据机构Id判断是否有用户
		/// </summary>
		/// <param name="orgId"></param>
		/// <returns></returns>
		public async Task<bool> HasUserOrg(long orgId)
		{
			return await _sysUserExtOrgRep.IsAnyAsync(u => u.OrgId == orgId);
		}
	}
}
